<%@ page language="java" contentType="text/javascript; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.Calendar"%>
<%@ page import="java.util.Date"%>
<%@ page import="java.text.DecimalFormat"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@page import='java.sql.*' %>
<%@page import="java.util.ArrayList"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="net.sf.json.JSONSerializer"%>
<%@page import="net.sf.json.JSONArray"%>
<%@page import="com.google.android.gcm.server.*" %>
<%@page import="javapns.communication.ConnectionToAppleServer"%>
<%@page import="javapns.devices.implementations.basic.BasicDevice"%>
<%@page import="javapns.notification.AppleNotificationServerBasicImpl"%>
<%@page import="javapns.notification.PushNotificationManager"%>
<%@page import="javapns.notification.PushNotificationPayload"%>
<%@page import="javapns.notification.PushedNotification"%>
<%@page import="javapns.notification.ResponsePacket"%>

<%String callback = request.getParameter("callback");%>
<%=callback %> (<%
	
	String userid = request.getParameter("userid");
	String username = new String(request.getParameter("username").getBytes("8859_1"), "utf-8");
	String usercacao = new String(request.getParameter("usercacao").getBytes("8859_1"), "utf-8");
	String num = request.getParameter("num");
	String hostid = request.getParameter("hostid");
	String hostname = new String(request.getParameter("hostname").getBytes("8859_1"), "utf-8");
	String msg = username + "님이 Ting에 참가하였습니다.<br><br>카카오톡 ID:"+usercacao;
	String date = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
	String time = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date());
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	PreparedStatement regpstmt = null;
	
	try{
		Class.forName("com.mysql.jdbc.Driver");
		conn = DriverManager.getConnection("jdbc:mysql://localhost/itscreater", "itscreater", "campus123");
		
		String select = "select * from TingAttendee where ID = ? and TingNumber = ?";
		pstmt = conn.prepareStatement(select);
		pstmt.setString(1, userid);
		pstmt.setString(2, num);
		ResultSet rs = pstmt.executeQuery();
		JSONObject jo = new JSONObject();
		
		if (rs.next()) {
			jo.put("success", "false");
		} else {
		
			String insert = "insert into TingAttendee " + "(TingNumber, ID) " +
										"values (?, ?);";
			pstmt = conn.prepareStatement(insert);
			pstmt.setString(1, num);
			pstmt.setString(2, userid);
			pstmt.executeUpdate();
			
			String sendjoinmsg = "insert into Message" +
					"(SenderID, Sender, GetterID, Getter, Message, Confirm, Date, Time)" +
					"values (?, ?, ?, ?, ?, ?, ?, ?);";
					
			pstmt = conn.prepareStatement(sendjoinmsg);
			pstmt.setString(1, userid);
			pstmt.setString(2, username);
			pstmt.setString(3, hostid);
			pstmt.setString(4, hostname);
			pstmt.setString(5, msg);
			pstmt.setInt(6, 0);
			pstmt.setString(7, date);
			pstmt.setString(8, time);
			pstmt.executeUpdate();
			
			String regidselect = "select * from gcm where ID = ?;";
			regpstmt = conn.prepareStatement(regidselect);
			regpstmt.setString(1, hostid);
			ResultSet regrs = regpstmt.executeQuery();
			
			while (regrs.next()){
				if (regrs.getInt("Device") == 0) {
					String regid = regrs.getString("regid");
					String push = regrs.getString("Push");
					String vibrate = regrs.getString("Vibrate");
					Sender sender = new Sender("AIzaSyC71UD8FmXiaATQ1FUv6fQalDzkMv4qBpg");
					Message message = new Message.Builder()
							//.collapseKey(MESSAGE_ID)
							//.delayWhileIdle(SHOW_ON_IDLE)
							//.timeToLive(LIVE_TIME)
							.addData("push", push)
							.addData("vibrate", vibrate)
							.build();
					Result result = sender.send(message, regid, 5);

					//if(result.getMessageId() != null) {
						
					//} else {
						//String error = result.getErrorCodeName(); 
					//}
				} else if (regrs.getInt("Device") == 1) {
					String regid = regrs.getString("regid");
					
					String host = "gateway.push.apple.com";
					int port = 2195;
					
					String certi = "www/Triends/SUDTriends.p12";
					String passwd = "SUDadventurer2";
					
					PushNotificationPayload payload = new PushNotificationPayload();
					payload.addAlert("쪽지가 왔습니다.");
					//payload.addBadge();
					payload.addSound("default");
					payload.addCustomDictionary("sign", "PushMagic");
					
					BasicDevice device = new BasicDevice(regid);
					device.setDeviceId("iphone");
					
					PushNotificationManager push = new PushNotificationManager();
					
					AppleNotificationServerBasicImpl appleserver = new AppleNotificationServerBasicImpl(certi, passwd, ConnectionToAppleServer.KEYSTORE_TYPE_PKCS12, host, port);
					push.initializeConnection(appleserver);
						
					PushedNotification pushed = push.sendNotification(device, payload);
					
					ResponsePacket resultPacket = pushed.getResponse();
					
					//if (resultPacket != null) {
						//boolean error = resultPacket.isErrorResponsePacket();
						//boolean error2 = resultPacket.isValidErrorMessage();
						//int error3 = resultPacket.getStatus();
						//String error4 = resultPacket.getMessage();
					//}
					push.stopConnection();
				}
			}
		}
		jo.put("success", "true");
		out.print(jo);
	}
	finally{
		try{
			pstmt.close();
		}
		catch (Exception ignored){
		}
		try{
			regpstmt.close();
		}
		catch (Exception ignored){
		}
		try{
			conn.close();
		}
		catch (Exception ignored){
		}
	}
%>);